var app=getApp();
var that = this;
var c
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: '',
    userInfo: null,
    openid2 :null,
    avatarUrl2:"",
    nickName2:"",
    openid:null,
    scrollTop:0,//控制上滑距离
    windowHeight: '',//页面高度
  },
  
  /**
   * 生命周期函数--监听页面加载
   */

  onReady: function() {

    var height = wx.getSystemInfoSync().windowHeight;
    this.setData({
      windowHeight: height,
      scrollTop:height
    })
    this.pageScrollToBottom();
  

    
  },
 
  // 获取容器高度，使页面滚动到容器底部
  pageScrollToBottom: function() {
    var that = this;
    var height = wx.getSystemInfoSync().windowHeight;
    wx.createSelectorQuery().select('#page').boundingClientRect(function(rect) {
      if (rect){
        that.setData({
          windowHeight: height,
          scrollTop: rect.height+50000
        })
      }
    }).exec()
  },


  onShow(){
    this.pageScrollToBottom()
    this.setData({
      interval:setInterval(function () {
        that.updateData()
      }, 1000) //循环时间 这里是1秒 
    })
  },
  async onLoad(options) {
    that=this
    //如果未登陆，则跳转到登陆界面
    if(!await app.hasUserInfo()){
      wx.navigateTo({
        url: '/pages/login/login'
      })
    }
    //设置聊天框名字为对方名字
    wx.setNavigationBarTitle({
      title: options.nickName2,
    })
   //自动下滑
   
    that.openid2 = options.openid2
    that.nickName2 = options.nickName2
    that.avatarUrl2 = options.avatarUrl2
    //传递参数为聊天对象的openid，nickname和头像
    that.setData({
      openid2:that.openid2,
      nickName2:that.nickName2,
      avatarUrl2:that.avatarUrl2,
      avatarUrl: app.globalData.userInfo.avatarUrl,
      userInfo:  app.globalData.userInfo,
      openid:app.globalData.userInfo.openid
    })

    //连接数据库  
    const db = wx.cloud.database({
      env: "cloud2-4gncvam39e2323e9",
    })
    that.updateData()
  //更新未读消息
    that.updatelastchat()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    that.updateData()
  },
 
  async updateData(){
    wx.hideNavigationBarLoading(); //隐藏加载
    //查询自己聊天记录
    this.db = wx.cloud.database({
      env: "cloud2-4gncvam39e2323e9",
    })
    const db = this.db
    const _ = db.command
    const openid= app.globalData.userInfo.openid
    const { data: initList } = await db.collection("chatroom").where(_.or([
      {
       openid2:this.data.openid2,
       _openid:openid
    },
    {
      openid2:openid,
      _openid:this.data.openid2
    }
  ])
    ).orderBy('sendTimeTS', 'desc').get()
    this.setData({
      state: initList.reverse(),
    })
  },
  onUnload() {
    //页面销毁停止运行
    let that = this
    clearInterval(that.data.interval)
      //更新未读消息
    that.updatelastchat()
  },
  onHide:function(){ 
		let that = this;
		clearInterval(that.data.interval);
  },
  //发送文字聊天
  async onConfirmSendText(e) {
    //如果文字框为空则不执行发送
    this.try(async () => {
      if (!e.detail.value) {
        return
      }
      //清空聊天框
      this.setData({
        textInputValue: ''
      })
      //聊天消息入数据库
      this.db = wx.cloud.database({
        env: "cloud2-4gncvam39e2323e9",
      })
      const db = this.db
      const _ = db.command
      const doc = {
        _id: `${Math.random()}_${Date.now()}`,
        avatar: this.data.userInfo.avatarUrl,
        nickName: this.data.userInfo.nickName,
        msgType: 'text',
        openid2:this.data.openid2,
        textContent: e.detail.value,
        sendTime: new Date(),
        sendTimeTS: Date.now(), // fallback
      }
      await db.collection("chatroom").add({
        data: doc,
      })
      
      this.pageScrollToBottom()
      //更改两人最后一条聊天记录 
      wx.cloud.callFunction({
        name:"updatelastchat",
        data:{
        avatar: this.data.avatarUrl2,
        nickName:this.data.nickName2,
        msgType: 'text',
        openid2:this.data.openid2,
        openid1:this.data.openid,
        textContent: e.detail.value,
        sendTime: new Date(),
        sendTimeTS: Date.now(), // fallback
        toroom:0,
        }
      })
      if(this.data.openid!=this.data.openid2){
      wx.cloud.callFunction({
        name:"updatelastchat",
        data:{
        avatar:  this.data.userInfo.avatarUrl,
        nickName: this.data.userInfo.nickName,
        msgType: 'text',
        openid2:this.data.openid,
        openid1:this.data.openid2,
        textContent: e.detail.value,
        sendTime: new Date(),
        sendTimeTS: Date.now(), // fallback
        toroom:0,
        }
      })
    }
      //更新接收者的数据*/
      }, '发送文字失败')
  },
  
  //发送照片
  async sendImage(e) {
    wx.chooseImage({
      count: 1,//最多一张图片 
      sourceType: ['album', 'camera'],//图片来源
      success: async res => {
       // const { envId, collection } = this.properties
       const envId =  "cloud2-4gncvam39e2323e9"
        const doc = {
          _id: `${Math.random()}_${Date.now()}`,
          avatar: this.data.userInfo.avatarUrl,
          nickName: this.data.userInfo.nickName,
          msgType: 'image',
          openid2:this.data.openid2,
          sendTime: new Date(),
          sendTimeTS: Date.now(), // fallback
        }

        const uploadTask = wx.cloud.uploadFile({
          cloudPath: `${this.data.openid}/${Math.random()}_${Date.now()}.${res.tempFilePaths[0].match(/\.(\w+)$/)[1]}`,
          filePath: res.tempFilePaths[0],
          config: {
            env: envId,
          },
          success: res => {
            this.try(async () => {
              await this.db.collection("chatroom").add({
                data: {
                  ...doc,
                  imgFileID: res.fileID,
                },
              })
                //更改两人最后一条聊天记录 
              wx.cloud.callFunction({
                name:"updatelastchat",
                data:{
                avatar: this.data.avatarUrl2,
                nickName:this.data.nickName2,
                msgType: 'text',
                openid2:this.data.openid2,
                openid1:this.data.openid,
                textContent: "  【图片】",
                sendTime: new Date(),
                sendTimeTS: Date.now(), // fallback
                toroom:0,
                }
              })
              if(this.data.openid!=this.data.openid2){
              wx.cloud.callFunction({
                name:"updatelastchat",
                data:{
                avatar:  this.data.userInfo.avatarUrl,
                nickName: this.data.userInfo.nickName,
                msgType: 'text',
                openid2:this.data.openid,
                openid1:this.data.openid2,
                textContent:"  【图片】",
                sendTime: new Date(),
                sendTimeTS: Date.now(), // fallback
                toroom:0,
                }
              })
            }
            //自动下拉到底部
            this.pageScrollToBottom();
            }, '发送图片失败')
          },
          fail: e => {
            this.showError('发送图片失败', e)
          },
        })
        //上传结束的回调函数
        uploadTask.onProgressUpdate(({ progress }) => {
      
        })
      },
    })
  },


  async try(fn, title) {
    try {
      await fn()
    } catch (e) {
      this.showError(title, e)
    }
  },
  //错误显示
  showError(title, content, confirmText, confirmCallback) {
    console.error(title, content)
    wx.showModal({
      title,
      content: content.toString(),
      showCancel: confirmText ? true : false,
      confirmText,
      success: res => {
        res.confirm && confirmCallback()
      },
    })
  },
  updatelastchat(){
    wx.cloud.callFunction({
       name:"updatelastchat",
       data:{
         openid2:that.openid2,
         openid1:getApp().globalData.userInfo.openid,
         toroom:1,
       }
       })
  },
  onMessageImageTap(e) {
    wx.previewImage({
      urls: [e.target.dataset.fileid],
    })
  },
  
})